from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.util import flatatt
from django.utils.safestring import mark_safe
from Captcha import PersistentFactory
from Captcha.Visual import ImageCaptcha

from captchas.examples import DefaultCaptcha


class CaptchaWidget(forms.TextInput):
    def _get_captcha_class(self):
        captcha_class = DefaultCaptcha
        if hasattr(settings, 'CAPTCHA_DEFAULT_CLASS'):
            module_name, cls_name = settings.CAPTCHA_DEFAULT_CLASS.rsplit('.', 1)
            try:
                module = __import__(module_name, fromlist=cls_name)
                captcha_class = getattr(module, cls_name, None)
                if captcha_class is None:
                    raise ImportError
            except ImportError:
                raise ImportError('Error importing custom captcha class "%s": '
                                  'check your CAPTCHA_DEFAULT_CLASS '
                                  'setting.' % settings.CAPTCHA_DEFAULT_CLASS)
            if not issubclass(captcha_class, ImageCaptcha):
                raise ImportError('Error importing custom captcha class "%s": '
                                  '%s is not a ImageCaptcha subclass.' %
                                  (settings.CAPTCHA_DEFAULT_CLASS, cls_name))
        return captcha_class

    def render(self, name, value, attrs=None):
        factory = PersistentFactory(settings.CAPTCHA_PERSISTENCE)
        test = factory.new(self._get_captcha_class())
        factory.storedInstances.close()
        text_input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        image_path = reverse('captcha_image', None, [test.id])
        return mark_safe(u'<img src="%s" border="0"/>'
                         u'<input type="hidden" name="captchaid" value="%s" />'
                         u'<input%s />'
                         % (image_path, test.id, flatatt(text_input_attrs)))

    def value_from_datadict(self, data, files, name):
        return [data[name], data['captchaid']]
